package no.uib.hplims.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

import no.uib.hplims.models.MyOrder;
import no.uib.hplims.models.Peptide;
import no.uib.hplims.models.User;
import no.uib.hplims.models.peptideinformation.PeptideInformation;
import no.uib.hplims.models.peptideinformation.SampleProcessingType;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.vaadin.appfoundation.authentication.SessionHandler;
import org.vaadin.appfoundation.persistence.facade.FacadeFactory;

public class ImportLibraryData {

	HashMap<String, MyOrder> orders = new HashMap<String, MyOrder>();

	public ImportLibraryData() {

	}

	public boolean startImport(File file) {
		InputStream inputStream = null;

		try {
			inputStream = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			System.out.println("File not found in the specified path.");
			e.printStackTrace();
		}

		POIFSFileSystem fileSystem = null;

		try {
			fileSystem = new POIFSFileSystem(inputStream);

			HSSFWorkbook workBook = new HSSFWorkbook(fileSystem);
			HSSFSheet sheet = workBook.getSheetAt(0);

			Iterator<Row> rows = sheet.rowIterator();
			while (rows.hasNext()) {
				HSSFRow row = (HSSFRow) rows.next();

				if (row.getRowNum() >= 3) {
					MyOrder order = findOrder(row);

					createPeptide(order, row);
				}
			}

			// close inputstream when finished
			if (inputStream != null) {
				inputStream.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	private void createPeptide(MyOrder order, HSSFRow row) {
		String peptideName = null;
		String accNumber = null;
		String numberInPlate = null;
		String sequence = null;
		String quality = null;
		String comment = null;
		String mod = null;
		String optimized = null;
		String machine = null;
		String initials = null;
		String status = null;
		String spikeLevelCSF = null;
		
		peptideName = row.getCell(1).getStringCellValue();
		accNumber = row.getCell(2).getStringCellValue();
		numberInPlate = row.getCell(3).getStringCellValue();
		sequence = row.getCell(4).getStringCellValue();
		quality = row.getCell(5).getStringCellValue();
		System.out.println(peptideName + " " + accNumber + " " + numberInPlate
				+ " " + sequence + " " + quality);

		if (row.getCell(6) != null) {
			if (row.getCell(6).getCellType() == Cell.CELL_TYPE_BLANK) {
				comment = "";
			} else if (row.getCell(6).getCellType() == Cell.CELL_TYPE_STRING) {
				comment = row.getCell(6).getStringCellValue();
			}
		}
		mod = row.getCell(7).getStringCellValue();
		optimized = row.getCell(8).getStringCellValue();
		if (row.getCell(9).getCellType() == Cell.CELL_TYPE_STRING) {
			machine = row.getCell(9).getStringCellValue();
		} else if (row.getCell(9).getCellType() == Cell.CELL_TYPE_NUMERIC) {
			machine = "" + row.getCell(9).getNumericCellValue();
		}
		initials = row.getCell(10).getStringCellValue();
		if (row.getCell(11) != null) {
			status = row.getCell(11).getStringCellValue();
		}

		if (row.getCell(12).getCellType() == Cell.CELL_TYPE_STRING) {
			spikeLevelCSF = row.getCell(12).getStringCellValue();
		} else if (row.getCell(12).getCellType() == Cell.CELL_TYPE_NUMERIC) {
			spikeLevelCSF = "" + row.getCell(12).getNumericCellValue();
		}
		
		Peptide peptide = new Peptide();
		peptide.setBelongsToOrder(order);
		peptide.setPeptideName(peptideName);
		peptide.setUniProtAccession(accNumber);
		peptide.setWellID(numberInPlate);
		peptide.setPeptideSequence(sequence);
		peptide.setSequenceLength(peptide.getPeptideSequence().length());
		
		PeptideInformation pi = new PeptideInformation();
		pi.setComment(comment);
		pi.setQuality(quality);
		pi.setModification(mod);
		pi.setMachine(machine);
		if (optimized.equalsIgnoreCase("y")) {
			pi.setOptimized(true);
		} else {
			pi.setOptimized(false);
		}
		pi.setInitials(initials);
		FacadeFactory.getFacade().store(pi);
		
		peptide.setPeptideInformationID(pi.getId());
		FacadeFactory.getFacade().store(peptide);
		
		order.addPeptide(peptide);
		FacadeFactory.getFacade().store(order);

	}

	private MyOrder findOrder(HSSFRow row) {
		System.out.print(row.getCell(0).getStringCellValue() + " ");
		System.out.println(row.getCell(1).getStringCellValue());

		String orderNumber = row.getCell(0).getStringCellValue();
		MyOrder order = null;
		if (orders.containsKey(orderNumber)) {
			order = orders.get(orderNumber);
			System.out.println("Order already exists. Getting...");
		} else {
			order = new MyOrder();
			order.setSalesOrderCode(orderNumber);
			order.setFinalized(true);
			order.setCreatedOn(new Date());
			order.setOwner((User) SessionHandler.get());
			FacadeFactory.getFacade().store(order);

			order.setOrderTitle("Imported order " + order.getId() + "  - "
					+ order.getSalesOrderCode());
			FacadeFactory.getFacade().store(order);

			orders.put(orderNumber, order);
			System.out.println("Order created.");
		}
		return order;
	}

}
